package com.ziroom.crm.mq.core.persistence;

import com.ziroom.crm.mq.core.MqType;
import com.ziroom.crm.mq.core.common.CommonConst;
import com.ziroom.crm.mq.core.config.MqConfig;
import com.ziroom.crm.mq.core.spi.SpiLoader;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * <p></p>
 * <p>
 * <PRE>
 * <BR>    修改记录
 * <BR>-----------------------------------------------
 * <BR>    修改日期         修改人          修改内容
 * </PRE>
 *
 * @author WeiShaoying
 * @version 1.0
 * @date Created in 2020年09月01日 14:33
 * @since 1.0
 */
@Slf4j
@SuppressWarnings("ALL")
public class PersistenceManager {

    /**
     * 不同类型不同实现类
     */
    private static final Map<String, Persistence> TYPE_PERSISTENCE_MAP = new ConcurrentHashMap<>(10);

    private static final Object LOCK = new Object();

    /**
     * 获取当前持久化处理类
     *
     * @return
     */
    public static Persistence getPersistence(MqType mqType) {
        return getPersistence(mqType, MqConfig.getConfig(MqConfig.PERSISTENCE_TYPE));
    }

    public static Persistence getPersistence(MqType mqType, String type) {
        String key = mqType + CommonConst.SYMBOL_MIDDLE_LINE + type;
        Persistence p = TYPE_PERSISTENCE_MAP.get(key);
        if (Objects.isNull(p)) {
            synchronized (LOCK) {
                p = TYPE_PERSISTENCE_MAP.get(key);
                if (Objects.isNull(p)) {
                    List<Persistence> persistenceList = SpiLoader.loadPrototypeInstanceListSorted(Persistence.class);
                    List<Persistence> list = persistenceList.stream()
                            .filter(persistence -> persistence.getType().equals(type) && persistence.getMqType().equals(mqType))
                            .collect(Collectors.toList());
                    if (list.size() == 0) {
                        log.error("未找到一个处理类,type:" + type + ",mqType:" + mqType + ".使用空处理");
                        p = new DefaultPersistence();
                    } else {
                        if (list.size() > 1) {
                            log.error("找到超过1个得处理类,type:" + type);
                        }
                        p = list.get(0);
                    }
                    TYPE_PERSISTENCE_MAP.put(key, p);
                }
            }
        }
        return p;
    }

}
